package com.xmy.service.impl;

import com.xmy.dao.BaseDao;
import com.xmy.entity.Sale;
import com.xmy.service.SaleService;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class SaleServiceImpl extends BaseDao implements SaleService {
    @Override
    public int addSaleInfo(Sale sale) {
        String sql = "INSERT INTO `shopdb`.`sale` (`id`, `price`, `quantity`, `totalPrice`,  `userId`, `productId`) VALUES (null, ?, ?, ?, ?, ?)";
        Object[] objects = {sale.getPrice(),sale.getQuantity(),sale.getTotalPrice(),sale.getUserId(),sale.getProductId()};
        return executeUpdate(sql,objects);
    }

    @Override
    public List<Sale> selAllSale(int page, int size) {
        String sql = "select * from sale limit ?,?";
        Object [] objects = {(page-1)*size,size};
        ResultSet rs = executeQuery(sql,objects);
        List<Sale> sales = new ArrayList<Sale>();
        try{
            while (rs.next()){
                Sale sale = new Sale();
                sale.setId(rs.getInt(1));
                sale.setPrice(rs.getDouble(2));
                sale.setQuantity(rs.getInt(3));
                sale.setTotalPrice(rs.getDouble(4));
                sale.setTime(rs.getDate(5));
                sale.setProductId(rs.getInt(6));
                sale.setUserId(rs.getInt(7));
                sales.add(sale);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return sales;
    }

    public int selCount(){
        String sql = "select count(1) from sale";
        ResultSet rs = executeQuery(sql,null);
        int count = 0;
        try {
            rs.next();
            count = rs.getInt(1);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }
}
